package com.zll.dms.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zll.dms.pojo.ResultData;
import com.zll.dms.utils.CosrUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 重写未认证之后逻辑
 * 弃用
 */
@Deprecated
public class MyAuthenticatingFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //处理options请求
        if (request instanceof HttpServletRequest) {
            if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
                return true;
            }
        }
        //如果不是option请求则调用父类方法处理
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //是配置的登录页面则调用原来逻辑
        //但一般不会到这里，登录配置的是不校验
        if (this.isLoginRequest(request, response)) {
            return super.onAccessDenied(request, response);
        }else {
            //没认证则直接返回json（status=402）
            //系统重定向会默认把请求头清空，这里通过拦截器重新设置请求头，解决跨域问题！！
            HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
            HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
            CosrUtils.handlerCosr(httpServletResponse, httpServletRequest);
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            PrintWriter writer = httpServletResponse.getWriter();
            ResultData noLogin = ResultData.createNoLogin();
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(noLogin);
            writer.println(s);
            writer.flush();
            writer.close();
//            httpServletResponse.sendRedirect("/auth/noLogin");
            return false;
        }

    }
}
